<?php
// https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
class Solution {
    function getIntersectionNode($headA, $headB) {
        if ($headA == null || $headB == null) {
            return null;
        }

        //先判断是否相交，不相交直接返回
        if(!$this->isIntersect($headA, $headB)){
            return null;
        }

        $p1 = $headA;
        $p2 = $headB;
        while ($p1 || $p2) {
            if ($p1 === $p2) {
                break;
            }
            $p1 = ($p1 == null) ? $headB : $p1->next;
            $p2 = ($p2 == null) ? $headA : $p2->next;
        }

        return $p1;
    }

    //判断是否相交
    function isIntersect($headA, $headB){
        if($headB == null || $headB == null){
            return false;
        }
        while($headA->next != null){
            $headA = $headA->next;
        }
        while($headB->next != null){
            $headB = $headB->next;
        }
        return $headA === $headB;
    }
}